package com.google.code.jtasks.server.startup;

import com.google.code.jtasks.server.GuiceConfig;
import com.google.inject.servlet.GuiceFilter;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;

import javax.servlet.DispatcherType;
import java.util.EnumSet;

/**
 * Server entry point.
 */
public class Main {
    private static final Logger LOG = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws Exception {
        LOG.info("Installing handlers for root logger");
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        LOG.info("Starting server");
        Server server = setupServer(8080);
        server.start();
        LOG.info("Server started");

        LOG.info("Now you can press Enter to stop the server");
        System.in.read();
        server.stop();
    }

    /**
     * Configures and starts Jetty server which will run Jersey REST service.
     *
     * @param port TCP port on which the server should listen
     * @return server instance
     */
    private static Server setupServer(int port) {
        FilterHolder filterHolder = new FilterHolder();
        filterHolder.setHeldClass(GuiceFilter.class);

        ServletHolder servletHolder = new ServletHolder();
        servletHolder.setHeldClass(EmptyServlet.class);

        ServletContextHandler servletContextHandler = new ServletContextHandler();
        servletContextHandler.setContextPath("/");
        servletContextHandler.addEventListener(new GuiceConfig());
        servletContextHandler.addServlet(servletHolder, "/*");
        servletContextHandler.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class));

        Server server = new Server(port);
        server.setHandler(servletContextHandler);
        return server;
    }

}
